package com.tangsm.springboot.redisson.demo.runner;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.tangsm.springboot.redisson.demo.domain.Order;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
public class RedissonRunner implements ApplicationRunner {

    @Autowired
    RedissonClient redissonClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        RBlockingQueue<Order> blockingQueue = redissonClient.getBlockingQueue("delay_queue");

        ThreadUtil.execAsync(() -> {
            while (true) {
                Order order = blockingQueue.poll();
                if (ObjectUtils.isEmpty(order)) {
                    try {
                        Thread.sleep(1000);
                        continue;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(StrUtil.format("当前时间:[{}],订单号:[{}],订单时间:[{}]", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss:SSS"), order.getOrderNo(), order.getCreateDate()));
            }
        });
    }
}